<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <template>
      <a-card class="mb20">
        <titleName title="基础信息填写" />
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
          :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
        >
          <a-row :gutter="24">
                  <a-col :md="16" :sm="16">
                      <a-form-model-item label="所属单位" prop="projectId" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                                         :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                          <org-tree-select v-model="form.projectId" disabled  checkStrictly
                                           :is-query-projec-detail="false">
                        </org-tree-select>
                      </a-form-model-item>
                  </a-col>
            <!-- <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="所属分公司："
                prop="branchComId"
              >
                <SelectSubCompany
                  v-model="form.branchComId"
                  :disabled="type == 'look'"
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="所属项目："
                prop="projectId"
              >
                <SelectProject
                  v-model="form.projectId"
                  :disabled="type == 'look'"
                  placeholder="请选择"
                  :form="form"
                  :is-clear="id == ''"
                  key-value="branchComId"
                  @selectChange="(e) => (form.name = e.name + '总包结算报送')"
                  @change="handleChange"
                />
              </a-form-model-item>
            </a-col> -->

            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="名称："
                prop="name"
              >
                <BaseInput
                  v-model="form.name"
                  :disabled="type == 'look'"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="发包人全称："
                prop="developerFullName"
              >
                <BaseInput
                  v-model="form.developerFullName"
                  disabled
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="结构类型："
                prop="structureType"
              >
                <BaseInput
                  v-model="form.structureType"
                  disabled
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="建筑面积(㎡)"
                prop="constructionArea"
              >
                <BaseInput
                  v-model="form.constructionArea"
                  :disabled="type == 'look'"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="送审结算书日期："
                prop="submitDate"
              >
                <a-date-picker
                  v-model="form.submitDate"
                  :disabled="type == 'look'"
                  @change="(date, dateString) => getTime(date, dateString, 'form', 'submitDate')"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="审批程序最迟期限："
                prop="auditLastDate"
              >
                <a-date-picker
                  v-model="form.auditLastDate"
                  :disabled="type == 'look'"
                  @change="(date, dateString) => getTime(date, dateString, 'form', 'auditLastDate')"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="开/竣工时间："
                prop="startCompletedTime"
              >
                <BaseInput
                  v-model="form.startCompletedTime"
                  disabled
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="合同造价（元）："
                prop="contractCost"
              >
                <BaseInputNumber
                  v-model="form.contractCost"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="实际成本（元）："
                prop="actCost"
              >
                <BaseInputNumber
                  v-model="form.actCost"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="财务已列报收入（元）："
                prop="recordIncome"
              >
                <BaseInputNumber
                  v-model="form.recordIncome"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="已收款（元）："
                prop="paidFor"
              >
                <BaseInputNumber
                  v-model="form.paidFor"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="结算保底值（元）："
                prop="settleMinAmount"
              >
                <BaseInputNumber
                  v-model="form.settleMinAmount"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="其中：设计变更/签证索赔（元）："
                prop="signClaimAmount"
              >
                <BaseInputNumber
                  v-model="form.signClaimAmount"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="结算预估值（元）："
                prop="settleEstAmount"
              >
                <BaseInputNumber
                  v-model="form.settleEstAmount"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="调整后报审值："
                prop="adjustedAmount"
              >
                <BaseInputNumber
                  v-model="form.adjustedAmount"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="合同约定结算书报出日期："
                prop="reportedDate"
              >
                <a-date-picker
                  v-model="form.reportedDate"
                  :disabled="type == 'look'"
                  @change="(date, dateString) => getTime(date, dateString, 'form', 'reportedDate')"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="8"
            >
              <a-form-model-item
                label="潜在违约及反索赔额（元）："
                prop="breakClaimAmount"
              >
                <BaseInputNumber
                  v-model="form.breakClaimAmount"
                  :max="99999999999999"
                  :disabled="type == 'look'"
                  :min="0"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <div />
            <a-col
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="承办范围"
                prop="undertakeRange"
                :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"
                :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
              >
                <BaseTextarea
                  v-model="form.undertakeRange"
                  :disabled="type == 'look'"
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
<!--            <a-col-->
<!--                    :md="24"-->
<!--                    :sm="24"-->
<!--            >-->
<!--              <a-form-model-item-->
<!--                      label="填报人"-->
<!--                      :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"-->
<!--                      :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"-->
<!--              >-->
<!--              <base-input v-model="form.createName" disabled></base-input>-->
<!--              </a-form-model-item>-->
<!--            </a-col>-->
            <a-col
              v-if="type != 'look'"
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="附件上传"
                :label-col="{ lg: { span: 3 }, sm: { span: 5 } }"
                :wrapper-col="{ lg: { span: 18 }, sm: { span: 17 } }"
              >
                <l-table
                  v-if="isUpdate"
                  :upload-arrys="form.fileInfoVOList"
                  business-code="BM03"
                  @fileArrysData="fileArrysData"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              v-else
              :md="24"
              :sm="24"
            >
              <a-form-model-item
                label="附件："
                prop="branchComId"
              >
                <file-link :file-list="form.fileInfoVOList" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>

      <div
        v-if="type != 'look'"
        class="tool-btns page-btn-right-top"
      >
        <a-button
          :loading="loading.DRAFT"
          type="primary"
          @click="submitForm('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          :loading="loading.SUBMITTED"
          type="primary"
          @click="submitForm('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="closeForm()"
        >
          关闭
        </a-button>
      </div>

      <div
        v-else
        class="tool-btns page-btn-right-top"
      >
        <a-button
          v-if="checkVisibleInDetail"
          type="primary"
          @click="closeForm()"
        >
          关闭
        </a-button>
      </div>
    </template>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import {
    addProjectTotalApproval,
    getProjectTotalApproval,
    updateProjectTotalApproval,
    deleteProjectTotalApproval,
    getProjectInfo,
    getProjectPlanningList
} from '@/api/businessAffairs/revenueAndCost'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import Vue from 'vue'
export default {
    name: 'a' + Date.now(),
    components: {
        SelectSubCompany,
        SelectProject
    },
    data() {
        return {
            token: '',
            checkVisibleInDetail: checkVisibleInDetail(this),
            form: {
                name: '',
                constructionArea: '',
                structureType: '',
                developerFullName: '',
                startCompletedTime: ''
            },
            isUpdate: true,
            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                name: [{ required: true, message: '请输入名称' }],
                submitDate: [{ required: true, message: '请输入送审结算书日期' }],
                auditLastDate: [{ required: true, message: '请输入发审批程序最迟期限' }],
                contractCost: [{ required: true, message: '请输入合同造价（元）' }],
                actCost: [{ required: true, message: '请输入实际成本（元）' }],
                recordIncome: [{ required: true, message: '请输入财务已列报收入（元）' }],
                paidFor: [{ required: true, message: '请输入已收款（元）' }],
                settleMinAmount: [{ required: true, message: '请输入结算保底值（元）' }],
                signClaimAmount: [{ required: true, message: '请输入设计变更/签证索赔（元）' }],
                settleEstAmount: [{ required: true, message: '请输入结算预估值（元）' }],
                adjustedAmount: [{ required: true, message: '请输入调整后报审值（元）' }],
                reportedDate: [{ required: true, message: '请输入合同约定结算书报出日期' }],
                breakClaimAmount: [{ required: true, message: '请输入潜在违约及反索赔额（元）' }],
                undertakeRange: [{ required: true, message: '请输入承办范围' }],
                constructionArea: [{ required: true, message: '请输入建筑面积 ' }]
            },
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            planningBooks: [],
            id: '',
            type: '',
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
   async mounted() {
        this.token = Vue.getAcloudProvider().getAccessToken()
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            console.log(this.id)
            this.getProjectTotalApproval()
        }
        this.type = this.$route.query.type
        //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_construction_general_settle_audit_new')
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.type = 'look'
                    })
                }
            }
        }
    },
    methods: {
        //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId;
                this.form.projectDeptId = val[val.length - 1].projectDeptId
            }
        },
        getTime(date, dateString, type, name) {
            this[type][name] = dateString
            console.log(this[type][name])
        },
        fileArrysData: function (val) {
            this.form.fileInfoVOList = val
            console.log(val)
        },
        //获取项目详情
        handleChange(e) {
            console.log(e)
            if (!e) return

            this.getProjectInfo(e)
        },
        getProjectPlanningList(id) {
            let params = {
                projectId: id,
                pageNo: 1,
                pageSize: 10
            }
            getProjectPlanningList(params).then((res) => {
                if (res.code == '200') {
                    this.planningBooks = res.data
                    this.showTip()
                }
            })
        },
        showTip() {
            if (this.planningBooks.length == 0 && this.type != 'look') {
                this.$message.warning('请添加该项目责任书！')
                return true
            }
            return false
        },
        getProjectInfo(id) {

            if (!id) return
            this.getProjectPlanningList(id)
            let params = {
                projectId: id
            }
            getProjectInfo(params).then((res) => {
                // this.form.constructionArea = res.data.contractTotalArea
                // this.form.structureType = res.data.structureTypeName
                // this.form.developerFullName = res.data.constructionName
                // this.form.startCompletedTime = res.data.contractStartDate + '~' + res.data.contractEndDate
                if(!this.form.constructionArea) {
                  this.$set(this.form, 'constructionArea', res.data.contractTotalArea * 10000)
                }
                this.$set(this.form, 'structureType', res.data.structureTypeName)
                this.$set(this.form, 'developerFullName', res.data.constructionName)
                this.$set(this.form, 'startCompletedTime', res.data.contractStartDate + '~' + res.data.contractEndDate)
                console.log(this.form)
            })
        },
        // 删除草稿
        deleteDraft() {
          let obj = {
            id:this.id,
            type:1
          }
            let that = this
            that.$confirm({
                title: '温馨提示',
                content: '确定是否删除数据？',
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    return deleteProjectTotalApproval(obj)
                        .then((res) => {
                            that.$message.success('删除成功！')
                            that.closeForm()
                        })
                        .catch((res) => {
                            that.$message.warning('删除失败！')
                        })
                }
            })
        },

        getProjectTotalApproval() {
            let params = {
                id: this.id
            }
            this.isUpdate = false
            getProjectTotalApproval(params).then((res) => {
                this.isUpdate = true
                this.form = { ...res.data }
                this.form.createName = this.$userInfo().name
                this.getProjectInfo(this.form.projectId)
                console.log(this.form)
            })
        },

        // 提交表单
        submitForm(auditStatus) {
            this.setProcessConfig = null;
            // if (this.showTip()) return
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (isAttachment(this, auditStatus, this.form.fileInfoVOList)) return
                    this.loading[auditStatus] = true
                    this.form.auditStatus = auditStatus
                    this.form.fileIdList = this.form.fileInfoVOList
                    this.submitApprovalConfirm(auditStatus =='SUBMITTED' ? this.processConfig:6,(flag)=>{
                      if(!flag) {
                        this.loading[auditStatus] = false
                        return
                      }
                    if (this.id == '') {
                        addProjectTotalApproval(this.form).then((res) => {
                            this.loading[auditStatus] = false
                            if (res.code == '200') {
                                this.$message.success('提交成功')
                                if(auditStatus =='SUBMITTED') {
                                //提交时，返回id
                                    this.businessId = res.data.id;
                                    this.setProcessConfig = this.processConfig;
                                    return
                                }else{
                                this.closeForm()
                                }
                            }
                        })
                    } else {
                        updateProjectTotalApproval(this.form).then((res) => {
                            this.loading[auditStatus] = false
                            if (res.code == '200') {
                                this.$message.success(auditStatus === 'SUBMITTED' ? '提交成功' : '保存草稿成功')
                                if(auditStatus =='SUBMITTED') {
                                //提交时，返回id
                                    this.businessId = res.data.id;
                                    this.setProcessConfig = this.processConfig;
                                    return
                                }else{
                                this.closeForm()
                                }
                            }
                        })
                    }
                    })
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                    console.log('error submit!!')
                    return false
                }
            })
        },
        // 关闭表单
        closeForm() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.step-text {
    .ant-steps-item-title {
        width: 168px;
    }
}
.check-box {
    .ant-checkbox-group {
        margin-top: 1.5%;
        display: flex;
        justify-content: space-between;
    }
    .ant-checkbox-group-item {
        position: static !important;
    }
}
.f-col {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    text-align: left;
}
.f-col .ant-form-item-label {
    text-align: left;
}
.radio-box {
    .ant-radio-wrapper {
        position: static !important;
    }
    .ant-radio-group {
        margin-top: 3% !important;
        display: flex;
    }
}

.foot-btn {
    display: flex;
    justify-content: flex-end;
}
</style>
